//
//  HomeViewController.swift
//  weibo1
//
//  Created by changhongliang on 2017/7/21.
//  Copyright © 2017年 richinfo. All rights reserved.
//
// 苹果自带多行注释工具 Command + option + /

import UIKit
import SDWebImage
import UITableView_FDTemplateLayoutCell

class HomeViewController: BaseTableViewController{
    
    lazy var popoverAnimator = PopoverAnimator()
    var statues:[StatusViewModel]?
    ///缓存行高 key 微博ID ,value 对应的行高
    var rowHeightCache = [String: CGFloat]()
    
    let statuesCellID = "statuesCellID"
    
    /// 记录是否是上拉加载更多
    var pullupFlag = false
    ///queue
    let queue = DispatchQueue(label: "loadData")

    override func viewDidLoad() {
       
        super.viewDidLoad()
        //打开FPS
        FPSView.shared
        if !login {
            vistorView?.setupVisitorInfo(imageName: nil, title: "关注一些人，回这里看看有什么惊喜")
            return
        }
       
        //设置导航栏
        setupNavigationItem()
        //注册通知
        let showNotification = Notification.Name(PopoverAnimatorShowNotification)
        NotificationCenter.default.addObserver(self, selector: #selector(HomeViewController.change), name:showNotification , object: nil)
        let dissmissNotification = Notification.Name(PopoverAnimatorDismissNotification)
        NotificationCenter.default.addObserver(self, selector: #selector(HomeViewController.change), name: dissmissNotification, object: nil)
        //添加下拉刷新
        refreshControl = HLRefreshControl()
        self.tableView.contentOffset = CGPoint(x:0, y:-refreshControl!.frame.size.height)
        refreshControl?.addTarget(self, action: #selector(HomeViewController.loadStatuesData), for: UIControlEvents.valueChanged)
        // 注意点:beginRefreshing并不会触发loadData
        refreshControl?.beginRefreshing()
        //添加提示视图
        self.tipLabel.frame = CGRect(x: 0, y: -44 * 2, width: UIScreen.main.bounds.size.width, height: 44)
        navigationController?.navigationBar.insertSubview(tipLabel, at: 0)

       
        //
        NotificationCenter.default.addObserver(self, selector: #selector(HomeViewController.showPhotobrowser(notify:)), name: NSNotification.Name(rawValue: HLPhotoBrowserShow), object: nil)
        
        //设置数据源和代理
        self.tableView.dataSource = self
        self.tableView.delegate = self
        tableView.estimatedRowHeight = 100
        self.tableView.register(StatusCell.classForCoder(), forCellReuseIdentifier:"originalCell")
        self.tableView.register(StatusCell.classForCoder(), forCellReuseIdentifier:"forwardCell")
        //加载微博数据
        self.queue.async {
            self.loadStatuesData()
        }
    }
    
    
    func showPhotobrowser(notify: NSNotification){
        //0.进行安全校验
        guard let urls = notify.userInfo!["urls"] as? [NSURL] else {
            return
        }
        
        guard let path = notify.userInfo!["indexPath"] as? IndexPath else {
            return
        }
        // 1.创建图片浏览器
        let browserVC = PhotoBrowserViewController(urls: urls, path: path )
        present(browserVC, animated: true, completion: nil)
        
    }
    
    fileprivate func setupNavigationItem(){
        //1.初始化左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention", target: self, action:#selector(HomeViewController.leftButtonClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action:#selector(HomeViewController.rightButtonClick))
        //2.添加标题
        let titleButton = TitleButton()
        titleButton.setTitle("三十七度温暖 ", for: UIControlState.normal)
        titleButton.sizeToFit()
        titleButton.addTarget(self, action: #selector(HomeViewController.titleButtonClick(btn:)), for: UIControlEvents.touchUpInside)
        navigationItem.titleView = titleButton
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
        
    }
    
   func showTipView(count:Int)  {
    //0.设置提醒文字
    tipLabel.text = (count == 0) ? "没有更多微博数据": "刷新到\(count)条微博"
    //1.保存原来的frame
    let rect = tipLabel.frame
    //2.执行动画
    UIView.animate(withDuration: 2.0, animations: { 
        self.tipLabel.frame = CGRect(origin: CGPoint(x: 0, y: 44), size: rect.size)
    }) { (_) in
        UIView.animate(withDuration: 1.0, delay: 1.0, options: UIViewAnimationOptions(rawValue: 0), animations: { 
            self.tipLabel.frame = rect
        }, completion: nil)
    }
    
 }
    

       /// 提醒视图
    private lazy var tipLabel: UILabel = {
        // 1.创建UILabel
        let lb = UILabel()
        lb.textAlignment =  NSTextAlignment.center
        lb.textColor = UIColor.white
        lb.backgroundColor = UIColor.init(red: 246/255.0, green: 145/255.0, blue: 54/255.0, alpha: 1.0)
        return lb
    }()

}


//MARK:- 加载微博数据相关
extension HomeViewController{
    //加载微博数据
    func loadStatuesData(){
        var since_id = statues?.first?.status.idstr ?? "0"
        var max_id = "0"
        if pullupFlag {
            max_id =  (statues?.last?.status.idstr)!
            max_id = "\(Int(max_id)! - 1)"
            since_id = "0"
        }
        loadStatuesFromCache(since_id: since_id, max_id: max_id)
    }
    
    
    //从本地加载数据
    func loadStatuesFromCache(since_id:String, max_id: String)
    {
        //先从本地加载
        guard let userId = UserAccount.loadUserAccount()?.uid else {
            return
        }
        //1.拼接SQL语句
        var sql = "SELECT * FROM T_Status \n" +
        "WHERE userId = '\(userId)' \n"
        if since_id != "0" {
            sql += "AND  statusId > '\(since_id)' \n"
        }else if max_id != "0"
        {
            sql += "AND  statusId <= '\(Int(max_id)! - 1)' \n"
        }
        sql +=  "ORDER BY statusId DESC LIMIT 20;"
        //2.执行SQL语句查询结果
        SQLiteManger.shareInstance.dbQueue?.inDatabase({ (db) in
            do
            {
                //2.1执行SQL语句
                let result = try db.executeQuery(sql, values: nil)
                //2.2取出结果
                var models = [StatusViewModel]()
                while result.next()
                {
                    //2.2.1取出微博数据
                    let statusText = result.string(forColumn: "statusText")
                    let data = statusText?.data(using: String.Encoding.utf8)
                    //2.2.2将微博字典转化为微博模型
                    let dict = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
                    let statusViewModel = StatusViewModel(status: Status(dict: dict as! [String: AnyObject]))
                    statusViewModel.cellHeight = Layout.caculateHeight(status: statusViewModel.status)
                    models.append(statusViewModel)
                }
                // 2.判断本地是否有数据
                if models.count != 0
                {
                    if since_id != "0" {
                        self.statues = models + self.statues!
                    }else if max_id != "0" {
                        self.statues = self.statues! + models
                        
                    }else{
                        self.statues = models
                    }
                    DispatchQueue.main.async {
                        // 1.刷洗表格
                        self.tableView.reloadData()
                        HLLog("本地加载刷新数据")
                        //2.关闭下拉刷新
                        self.refreshControl?.endRefreshing()
                    }
                    
                }else {
                        loadStatuesFromNetwork(since_id: since_id, max_id: max_id)
                }
                
            }catch{
                HLLog(error)
            }
        })
    }
    
    
    //从网络加载数据
    func loadStatuesFromNetwork(since_id:String, max_id: String){
        let userAccount = UserAccount.loadUserAccount()
        NetworkTools.requestData(.get, URLString: "2/statuses/home_timeline.json", parameters: ["access_token":userAccount?.access_token ?? "","since_id": since_id ,"max_id":max_id ]) { (result, error) in
            if let resultStatues = result?["statuses"] as? Array<[String:AnyObject]>
            {
                // 2.遍历微博数组,处理微博数据
                var models = [StatusViewModel]()
                for dict in resultStatues {
                    let statusViewModel = StatusViewModel(status: Status(dict: dict ))
                    statusViewModel.cellHeight = Layout.caculateHeight(status: statusViewModel.status)
                    models.append(statusViewModel)
                }
                //3.处理下拉刷新数据
                if since_id != "0" {
                    self.statues = models + self.statues!
                }else if max_id != "0" {
                    self.statues = self.statues! + models
                    
                }else{
                    self.statues = models
                }
                DispatchQueue.main.async {
                    self.showTipView(count: models.count)
                }
                //缓存微博数据
                self.cacheStatues(list: resultStatues)
                //缓存图片数据
                self.cacheImage(list: models)
            }
        }
        
    }
    
    
    //缓存数据
    func cacheStatues(list:[[String:AnyObject]]) {
        guard let userId = UserAccount.loadUserAccount()?.uid else
        {
            return
        }
        SQLiteManger.shareInstance.dbQueue?.inTransaction({ (db, rollback) in
            for dict in list
            {
                //2.准备数据
                //2.0获取当前微博的ID
                guard let idStr = dict["idstr"] as? String else
                {
                    return
                }
                //2.1将字典转化为二进制
                guard let data = try? JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions.prettyPrinted) else
                {
                    break
                }
                //2.2将二进制转为化字符串
                guard let statusText = String(data: data, encoding: String.Encoding.utf8) else
                {
                    return
                }
                
                let sql = "INSERT INTO T_Status \n" +
                    "(statusId, statusText, userId) \n" +
                    "VALUES \n" +
                "(?, ?, ?);"
                
                do {
                    try db.executeUpdate(sql, values: [idStr,statusText,userId])
                    
                }catch{
                    HLLog(error)
                }
                
                
            }
        })
        
    }
    
    class func clearCacheStatus(){
        //1.获取当前时间的字符串
        let now = NSDate(timeIntervalSinceNow: -60)
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        formatter.locale = Locale(identifier: "en")
        let dateStr = formatter.string(from: now as Date)
        //2.根据时间编写SQL语句
        let sql = "DELETE FROM T_Status WHERE createDate <= '\(dateStr)';"
        //3.执行SQL语句
        SQLiteManger.shareInstance.dbQueue?.inTransaction({ (db,rollback) in
            try! db.executeUpdate(sql, values: nil)
        })
        
    }
    
    
    
    /// 缓存所有配图
    private func cacheImage(list: [StatusViewModel]){
        //0.创建一个组
        let grop = DispatchGroup()
        //1.取出所有的微博数据
        for statusViewModel in list {
            // 2.安全校验
            guard let urls = statusViewModel.thumbnail_pics else {
                continue
            }
            // 3.从微薄模型取出所有的配图字典
            for url in urls {
                // 将当前操作加入组中
                grop.enter()
                //4.下载图片
                //注意:downloadImageWithURL方法下载图片是在子线程,而回调是在主线程
               SDWebImageManager.shared().loadImage(with: url as URL, options: SDWebImageOptions(rawValue: 1), progress: nil, completed: { (image, data, error, _, _, url) in
                 grop.leave()
               })
                //  当这个循环执行完毕一次, 代表一条微博的配图全部下载完毕
            }
            // 当这个循环执行完毕, 代表全部微博的配图全部下载完毕
        }
        
        grop.notify(queue: DispatchQueue.main) {
            // 更新UI
            // 1.刷洗表格
            self.tableView.reloadData()
            //2.关闭下拉刷新
            self.refreshControl?.endRefreshing()
        }
        
    }
    
}



//MARK:- 按钮点击相关方法
extension HomeViewController{
    
    func leftButtonClick()  {
        HLLog("leftButtonClick")
    }
    
    func rightButtonClick() {
        HLLog("rigthButtonClick")
    }
    
    func titleButtonClick(btn:UIButton) {
        //设置转场动画
        let vc = FriendGroupViewController()
        vc.transitioningDelegate = popoverAnimator
        vc.modalPresentationStyle = UIModalPresentationStyle.custom
        present(vc, animated: true, completion: nil)
    }
    
    func change() {
        let titleButton = self.navigationItem.titleView as! TitleButton
        titleButton.isSelected = !titleButton.isSelected
    }
    
  }

///MARK: - tableView的数据源和代理方法
extension HomeViewController{
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.statues?.count ?? 0
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: HLTabelViewCellIdentifier.identifierWithViewModel(viewModel: (self.statues?[indexPath.row])!)) as!StatusCell
        cell.statusViewModel = self.statues?[indexPath.row]
        //判断是否是最后一个cell
        if indexPath.row == statues!.count - 1 {
            pullupFlag = true
            loadStatuesData()
        }
        return cell
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return CGFloat((self.statues?[indexPath.row].cellHeight)!)
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // 接收到内存警告, 将所有缓存移除
        rowHeightCache.removeAll()
    }
    

}


